import SparkMD5 from 'spark-md5'
import httpApi from '../http/index.js'


// 判断附件是否是图片
export function fileIsImgByName(name) {
	let type = getFileType(name);
	return [
		'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'
	].indexOf(type.toLowerCase()) !== -1;
}
// 判断附件是否是视频
export function fileIsVideoByName(name) {
	let type = getFileType(name);
	return [
		"avi", "wmv", "mpeg", "mp4", "m4v", "mov", "asf", "flv", "f4v", "rmvb", "rm", "3gp", "vob"
	].indexOf(type.toLowerCase()) !== -1;
}
// 判断附件是否是图片
export function fileIsImgByType(type) {
	return [
		'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'
	].indexOf(type.toLowerCase()) !== -1;
}
// 判断附件是否是视频
export function fileIsVideoByType(type) {
	return [
		"avi", "wmv", "mpeg", "mp4", "m4v", "mov", "asf", "flv", "f4v", "rmvb", "rm", "3gp", "vob"
	].indexOf(type.toLowerCase()) !== -1;
}
// 获取文件后缀
export function getFileType(name) {
	let index = name.lastIndexOf('.') + 1;
	return name.slice(index).toLowerCase()
}

export function fileIsVideoOrImgByType(type) {
	return fileIsVideoByType(type) || fileIsImgByType(type);
}

// 上传文件
export async function toUpload(file) {

	if (!file.MD5){
		file.MD5 = await getFileMD5(file)
	}
	file.MD5 = file.MD5 + '2'
	// 是否已上传过
	let {data} = await httpApi.checkFile({md5: file.MD5})
	if(data.data){
		return new Promise((resolve, reject) => { resolve({'data': data})})
	}

	// 如果文件小于5MB，直接上传
	if (file.size < 5 * 1024 * 1024) {
		let fetchForm = {
			'file': file,
			'md5': file.MD5
		};
		return httpApi.uploadFile(fetchForm)
	} else {
		// 如果文件大于等于10MB，分片上传
		return  shardUpload(file)
	}
}
// 分片上传
export async function shardUpload(file) {
	// 从第几片开始
	let index = 0;
	// 是否已上传过
	let {data} = await httpApi.shardCheckFile({md5: file.MD5})
	if(data.data){
		index = data.data
	}

	// 上传过程中用到的变量
	const chunkSize = 5 * 1024 * 1024; 						// 5MB一片
	const chunkCount = Math.ceil(file.size / chunkSize); 	// 总片数
	if(index >= chunkCount){
		index = chunkCount - 1
	}
	
	// 获取当前chunk数据
	const getChunkInfo = async (file, index) => {
		let start = index * chunkSize;
		let end = Math.min(file.size, start + chunkSize);
		let chunk = file.slice(start, end);
		return {start,end,chunk};	
	};
	


	// 针对单个文件进行chunk上传
	const readChunk = async (index, count) => {
		const {chunk} = await getChunkInfo(file, index);
		const fetchForm = {		
			'md5': file.MD5,
			'index': index,
			'fileSize': file.size,
			'shardCount': count,
			'name': file.name
		};
		return httpApi.shareUploadFile(chunk,fetchForm)
	};
	
	// 针对每个文件进行chunk处理
	const promiseList = [];
	try {
		// #ifdef APP-PLUS
		let cres = await appChunkUpload(file,chunkSize,chunkCount,promiseList)
		// #endif
		
		// #ifdef H5  || MP-ALIPAY || MP-WEIXIN
		for (index; index < chunkCount; ++index) {
			promiseList.push(readChunk(index, chunkCount))
		}
		// #endif
		
		const res = await Promise.all(promiseList);
		return httpApi.mergeFile({md5: file.MD5,shardCount: chunkCount});
	} catch (e) {
		return e
	}
}


// app 分片上传
function appChunkUpload(readyFile,chunkSize,chunkCount,promiseList){
	
	return new Promise((resolve, reject) => {
		const FileSpliter = uni.requireNativePlugin('Forke-FileSpliter');
		plus.io.resolveLocalFileSystemURL(readyFile.path, (entry) => {
			entry.file( (file) => {
				
				FileSpliter.splitFile({
					filePath: file.fullPath, 	//选择文件的完整路径，例如"/storage/0/..."
					savePath: plus.io.convertLocalFileSystemURL("_doc/FileSpliter"), //保存文件的完整路径，需要该路径存在, 例如"/storage/0/..."
					fileName: file.name, 		//"文件名"  
					chunkSize: chunkSize,  //每一片的大小, 例如 1024 * 1024 * 10  代表10MB
				}, (ret) => {
					//成功的回调
					if (ret) {
						if (ret.code == 'process') {
							console.log("name", ret); //分片的所属文件名，用于区分多文件同时切片
							const fetchForm = {
								'md5': readyFile.MD5,
								'index': ret.chunk,
								'fileSize': readyFile.size,
								'shardCount': chunkCount,
								'name': file.name
							};
							promiseList.push(httpApi.shareUploadFile(ret.path,fetchForm))
						} else if (ret.code == 'complete') {
							console.log("切片完成",ret);
							deleteFiles(file.name)
							resolve('ok');
						} else if (ret.code == 'start') {
							console.log("切片开始");
						}
					}
				}, (ret) => {
					//失败的回调
					reject(ret);
				});	
			})
		})
	})	
}

// 删除临时文件
function deleteFiles(fileName){
    const FileSpliter = uni.requireNativePlugin('Forke-FileSpliter');
    FileSpliter.clearFilePath({
            savePath: plus.io.convertLocalFileSystemURL("_doc/FileSpliter"),
            fileName: fileName
        }, (ret) => {
            if (ret) {
                if (ret.code == 'complete') {
                    console.log("切片目录已清空");
                }
            }
        }, (ret) => {
    
     });
}





// 获取文件的md5值
export function getFileMD5(file) {

	return new Promise((resolve, reject) => {

		// #ifdef APP-PLUS
		uni.getFileInfo({filePath: file.path,digestAlgorithm: 'md5'}).then((res)=>{
			resolve(res[1].digest);
		}).catch(e=>{
			reject(e);
		})
		// #endif

		// #ifdef H5  || MP-ALIPAY || MP-WEIXIN
		let spark = new SparkMD5();
		let fileReader = new FileReader();
		//将文件进行分块 file.slice(start,length)
		if (file.size > 1024 * 1024 * 10) {
			let fileSlice = file.slice(0, 1024 * 1024 * 10);
			fileReader.readAsBinaryString(fileSlice); //将文件读取为二进制码
		} else {
			fileReader.readAsBinaryString(file);
		}

		//创建md5对象（基于SparkMD5）
		fileReader.onload  = function(e) {
			spark.appendBinary(e.target.result);
			let md5 = spark.end();
			resolve(md5);
		};
		fileReader.onerror = function(e) {
			reject(e);
		};
		// #endif
	})
}
